/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import DTO.Customers.Customer;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.apache.avalon.framework.logger.ConsoleLogger;
import org.apache.avalon.framework.logger.Logger;
import org.apache.fop.apps.Driver;
import org.apache.fop.apps.FOPException;
import org.xml.sax.InputSource;

/**
 *
 * @author ThanhTai
 */
public class ConvertToPDF extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, TransformerException {
        response.setContentType("text/html;charset=UTF-8");
        {
            try {
                request.setCharacterEncoding("UTF-8");
                HttpSession session = request.getSession();
                Customer customer = (Customer) session.getAttribute("USER");
                String path = getServletContext().getRealPath("/");
                String xmlPathCart = path + "xml/cart_"+ customer.getCustEmail().trim() +".xml";
                String xmlPathUser = path + "xml/user_"+ customer.getCustEmail().trim() + ".xml";
                String foPath = path + "fo/shipping.fo";
                String xslPath = path + "xsl/shippingFO.xsl";
                methodTrAX(xslPath, xmlPathUser, xmlPathCart, foPath, path);
                File file = new File(foPath);
                FileInputStream input = new FileInputStream(file);
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                response.setContentType("application/pdf");
                Driver driver = new Driver(new InputSource(input), out);
                Logger log = new ConsoleLogger(ConsoleLogger.LEVEL_WARN);
                driver.setRenderer(Driver.RENDER_PDF);
                driver.run();
                byte[] content = out.toByteArray();
                response.setContentLength(content.length);
                response.getOutputStream().write(content);
                response.getOutputStream().flush();
            }catch (FOPException ex) {
                java.util.logging.Logger.getLogger(ConvertToPDF.class.getName()).log(Level.SEVERE, null, ex);
            } catch (Exception ex) {
                java.util.logging.Logger.getLogger(ConvertToPDF.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
//                db.close();
            }
        }
    }

    private void methodTrAX(String xslPath, String xmlPathUser, String xmlPathCart, String output, String path) {
        try {
            TransformerFactory tf = TransformerFactory.newInstance();
            StreamSource xstlFile = new StreamSource(xslPath);
            Transformer trans = tf.newTransformer(xstlFile);
            String logoPath = path + "images/logo.jpg";
            trans.setParameter("pathFile", path);
            trans.setParameter("logoFile", logoPath);
            trans.setParameter("xmlUser", xmlPathUser);
            StreamSource xmlFile = new StreamSource(xmlPathCart);
            StreamResult htmlFile = new StreamResult(new FileOutputStream(output));
            trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            trans.transform(xmlFile, htmlFile);
        } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
        catch (TransformerException ex) {
            java.util.logging.Logger.getLogger(ConvertToPDF.class.getName()).log(Level.SEVERE, null, ex);
        } catch (FileNotFoundException ex) {
            java.util.logging.Logger.getLogger(ConvertToPDF.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (TransformerException ex) {
            java.util.logging.Logger.getLogger(ConvertToPDF.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (TransformerException ex) {
            java.util.logging.Logger.getLogger(ConvertToPDF.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
